package com.xmb.wechat.bean;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.blankj.utilcode.util.ConvertUtils;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.squareup.picasso.Picasso;
import com.xmb.wechat.R;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.common.Constant;
import com.xmb.wechat.entity.WechatAppInfoBean;
import com.xmb.wechat.picasso.PicassoRoundByPercentTransform;
import com.xmb.wechat.picasso.PicassoSizeFitTransform;

import java.io.Serializable;

import io.objectbox.annotation.Entity;
import io.objectbox.annotation.Id;
import io.objectbox.annotation.Transient;

/**
 * 微信好友
 */
@Entity
public class WechatContactBean implements Comparable<WechatContactBean>, Serializable {
    @Id
    long id;
    String  name;
    String  pingyin;//拼音
    String  firstLetter;
    String  avatar;
    int     avatarSrc;//头像图片来源：0-SDCard，1-APP内置
    String  chatBG;//聊天背景图
    boolean isMute;//消息免打扰
    boolean isStrongRemind;//强提醒
    boolean isInner;//系统
    int     groupSort;

    @Transient
    boolean isSelected;

    @Override
    public String toString() {
        return "WechatContactBean{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pingyin='" + pingyin + '\'' +
                ", firstLetter='" + firstLetter + '\'' +
                ", avatar='" + avatar + '\'' +
                ", avatarSrc=" + avatarSrc +
                ", chatBG='" + chatBG + '\'' +
                ", isMute=" + isMute +
                ", isStrongRemind=" + isStrongRemind +
                ", isInner=" + isInner +
                ", groupSort=" + groupSort +
                ", isSelected=" + isSelected +
                '}';
    }

    //创建一条我的数据(联系人)
    public static WechatContactBean instanceNewContactMe(Context context) {
        return instanceNewContactMe(context, true);
    }

    //创建一条我的数据(联系人)
    public static WechatContactBean instanceNewContactMe(Context context, boolean isShowMe) {
        WechatAppInfoBean myInfoBean = WechatAppInfoBean.getWechat(context);
        WechatContactBean me = new WechatContactBean();
        me.setId(-1);
        if (isShowMe)
            me.setName(myInfoBean.getName() + "（我）");
        else
            me.setName(myInfoBean.getName());
        me.setAvatarSrc(Constant.SourceType.AVATAR_SRC_SDCARD);
        me.setAvatar(myInfoBean.getAvatar());
        return me;
    }

    //创建一条我的数据(支付宝)
    public static WechatContactBean instanceNewAliPayMe(Context context) {
        return instanceNewAliPayMe(context, true);
    }

    //创建一条我的数据(支付宝)
    public static WechatContactBean instanceNewAliPayMe(Context context, boolean isShowMe) {
        WechatAppInfoBean myInfoBean = WechatAppInfoBean.getAliPay(context);
        WechatContactBean me = new WechatContactBean();
        me.setId(-1);
        if (isShowMe)
            me.setName(myInfoBean.getName() + "（我）");
        else
            me.setName(myInfoBean.getName());
        me.setAvatarSrc(Constant.SourceType.AVATAR_SRC_SDCARD);
        me.setAvatar(myInfoBean.getAvatar());
        return me;
    }

    //创建一条我的数据(qq)
    public static WechatContactBean instanceNewQQMe(Context context) {
        return instanceNewQQMe(context, true);
    }

    //创建一条我的数据(qq)
    public static WechatContactBean instanceNewQQMe(Context context, boolean isShowMe) {
        WechatAppInfoBean myInfoBean = WechatAppInfoBean.getQQ(context);
        WechatContactBean me = new WechatContactBean();
        me.setId(-1);
        if (isShowMe)
            me.setName(myInfoBean.getName() + "（我）");
        else
            me.setName(myInfoBean.getName());
        me.setAvatarSrc(Constant.SourceType.AVATAR_SRC_SDCARD);
        me.setAvatar(myInfoBean.getAvatar());
        return me;
    }

    //通过Id查询WechatContactBean(可查询自己)
    public static WechatContactBean getWechatContactBean(Context context, long wechatContactBeanId, boolean isShowWo) {
        Log.e("sana", "wechatContactBeanId=" + wechatContactBeanId);
        WechatContactBean result;
        if (wechatContactBeanId < 0) {
            if (wechatContactBeanId == -1)
                result = instanceNewContactMe(context, isShowWo);
            else//未负值
                result = null;
        } else {
            result = WechatStartApplication.getBoxStore().boxFor(WechatContactBean.class).query()
                    .equal(WechatContactBean_.id, wechatContactBeanId).build().findUnique();
        }
        return result;
    }

    /**
     * @param contactBean
     * @param iv
     * @param roundPercent 12
     */
    public static void setupAvatarIntoImageView(WechatContactBean contactBean, ImageView iv, int roundPercent) {
        if (contactBean == null)
            return;
        if (iv == null)
            return;
        setupAvatarIntoImageView(contactBean.getAvatarSrc(), contactBean.getName(), contactBean.getAvatar(), iv, roundPercent);
    }

    public static void setupAvatarIntoImageView(int avatarSrc, String name, String avatar, ImageView iv, int roundPercent) {
        //空Url
        if (TextUtils.isEmpty(avatar)) {
            Picasso.get().load(R.drawable.ic_wx_default_avatar)
                    .transform(new PicassoSizeFitTransform(ConvertUtils.dp2px(34)))
                    .transform(new PicassoRoundByPercentTransform(roundPercent)).into
                    (iv);
            return;
        }
        //非空Url
        switch (avatarSrc) {
            case Constant.SourceType.AVATAR_SRC_SDCARD:
                Picasso.get().load("file://" + avatar).error(R.drawable.ic_wx_default_avatar)
                        .transform(new PicassoSizeFitTransform(ConvertUtils.dp2px(34)))
                        .transform(new PicassoRoundByPercentTransform(roundPercent)).into
                        (iv);
                break;
            case Constant.SourceType.AVATAR_SRC_APP_INNER_ASSETS:
                String imgUrl = "file:///android_asset/avatars/" + avatar;
                Picasso.get().load(imgUrl).error(R.drawable.ic_wx_default_avatar)
                        .transform(new PicassoSizeFitTransform(ConvertUtils.dp2px(34)))
                        .transform(new PicassoRoundByPercentTransform(roundPercent)).into
                        (iv);
                break;
            case Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE:
                int res;
                if (TextUtils.equals("新的朋友", name)) {
                    res = R.drawable.ic_wx_contacts_new_friend;
                } else if (TextUtils.equals("群聊", name)) {
                    res = R.drawable.ic_wx_contacts_group_friend1380;
                } else if (TextUtils.equals("标签", name)) {
                    res = R.drawable.ic_wx_contact_tag;
                } else if (TextUtils.equals("公众号", name)) {
                    res = R.drawable.ic_wx_contacts_gzh;
                } else {
                    res = Integer.parseInt(avatar);
                }
                Picasso.get().load(res).error(R.drawable.ic_wx_default_avatar)
                        .transform(new PicassoSizeFitTransform(ConvertUtils.dp2px(34)))
                        .transform(new PicassoRoundByPercentTransform(roundPercent)).into
                        (iv);
                break;
        }
    }

    public static void setupAvatarIntoImageView(WechatContactBean contactBean, ImageView iv) {
        String avatar = contactBean.getAvatar();
        int avatarSrc = contactBean.getAvatarSrc();
        //空Url
        if (TextUtils.isEmpty(avatar)) {
            Picasso.get().load(R.drawable.ic_wx_default_avatar).into(iv);
            return;
        }
        //非空Url
        switch (avatarSrc) {
            case Constant.SourceType.AVATAR_SRC_SDCARD:
                Picasso.get().load("file://" + avatar).error(R.drawable.ic_wx_default_avatar).into(iv);
                break;
            case Constant.SourceType.AVATAR_SRC_APP_INNER_ASSETS:
                Picasso.get().load("file:///android_asset/avatars/" + avatar).error(R.drawable.ic_wx_default_avatar).into(iv);
                break;
        }
    }

    private void buildPinyin(String name) {
        if (!TextUtils.isEmpty(name)) {
            String firstChar = name.charAt(0) + "";
            if (firstChar.matches("^[0-9]+") || firstChar.matches("#")) {
                /**以数字和#开头的name都归于#*/
                pingyin = "zzzzzzzzzzzzzzzzzzzz";
                firstLetter = "#";
            } else {
                try {
                    this.pingyin = PinyinHelper.convertToPinyinString(name.trim(), "",
                            PinyinFormat.WITHOUT_TONE);
                } catch (PinyinException e) {
                    e.printStackTrace();
                }
                if (!TextUtils.isEmpty(pingyin)) {
                    char firstLetterChar = this.pingyin.toUpperCase().charAt(0);
                    firstLetter = firstLetterChar + "";
                    if (firstLetterChar < 'A' || firstLetterChar > 'Z') {
                        pingyin = "zzzzzzzzzzzzzzzzzzzz";
                        firstLetter = "#";
                    }
                }
            }

        } else {
            pingyin = "zzzzzzzzzzzzzzzzzzzz";
            firstLetter = "#";
        }
        firstLetter = firstLetter.toUpperCase();
    }

    //-------------------------------------------------------------------------Get&Set-------------------------------------------------------------------------

    public Boolean getInner() {
        return isInner;
    }

    public void setInner(Boolean inner) {
        isInner = inner;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public String getFirstLetter() {
        return firstLetter;
    }

    public void setFirstLetter(String firstLetter) {
        this.firstLetter = firstLetter;
    }

    public String getPingyin() {
        return pingyin;
    }

    public void setPingyin(String pingyin) {
        this.pingyin = pingyin;
    }

    public int getAvatarSrc() {
        return avatarSrc;
    }

    public void setAvatarSrc(int avatarSrc) {
        this.avatarSrc = avatarSrc;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        buildPinyin(name);//同时处理拼音
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public String getChatBG() {
        return chatBG;
    }

    public void setChatBG(String chatBG) {
        this.chatBG = chatBG;
    }

    public boolean isMute() {
        return isMute;
    }

    public void setMute(boolean mute) {
        isMute = mute;
    }

    public boolean isStrongRemind() {
        return isStrongRemind;
    }

    public void setStrongRemind(boolean strongRemind) {
        isStrongRemind = strongRemind;
    }

    public boolean isInner() {
        return isInner;
    }

    public void setInner(boolean inner) {
        isInner = inner;
    }

    public int getGroupSort() {
        return groupSort;
    }

    public void setGroupSort(int groupSort) {
        this.groupSort = groupSort;
    }


    //-------------------------------------------------------------------------compare------------------------------------------------------------------

    @Override
    public int compareTo(WechatContactBean o) {
        //箭头优先：
        if (o.getFirstLetter().equals("↑") && !getFirstLetter().equals("↑")) {
            return 1;
        } else if (!o.getFirstLetter().equals("↑") && getFirstLetter().equals("↑")) {
            return -1;
        } else if (o.getFirstLetter().equals("↑") && getFirstLetter().equals("↑")) {
            return (int) (getId() - o.getId());
        }
        return getPingyin().toUpperCase().compareTo(o.getPingyin().toUpperCase());
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        if (obj instanceof WechatContactBean) {
            WechatContactBean u = (WechatContactBean) obj;
            return this.id == u.id;
        }
        return super.equals(obj);
    }
}
